<?php

namespace catchAdmin\permissions\controller;

use app\common\lib\Redis;

use catchAdmin\permissions\excel\UserExport;
use catcher\base\CatchRequest;
use catcher\base\CatchRequest as Request;
use catchAdmin\permissions\model\Permissions;
use catchAdmin\permissions\model\Roles;
use catchAdmin\permissions\model\Users;
use catchAdmin\permissions\request\CreateRequest;
use catchAdmin\permissions\request\UpdateRequest;
use catchAdmin\permissions\request\ProfileRequest;
use catcher\base\CatchController;
use catcher\CatchAuth;
use catcher\CatchCacheKeys;
use catcher\CatchResponse;
use catcher\exceptions\FailedException;
use catcher\library\excel\Excel;
use catcher\Tree;
use catcher\Utils;
use think\facade\Cache;
use think\facade\Db;

class User extends CatchController
{
    protected $user;

    public function __construct(Users $user)
    {
        $this->user = $user;
    }

    /**
     *
     * @time 2020年04月24日
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        return CatchResponse::paginate($this->user->getList());
    }

    /**
     * 获取用户信息
     *
     * @time 2020年01月07日
     * @param CatchAuth $auth
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function info(CatchAuth $auth)
    {
        $user = $auth->user();

        $roles = $user->getRoles()->column('identify');

        $permissionIds = $user->getPermissionsBy($user->id);
        // 缓存用户权限
        Cache::set(CatchCacheKeys::USER_PERMISSIONS . $user->id, $permissionIds);

        $user->permissions = Permissions::getCurrentUserPermissions($permissionIds);

        $user->roles = $roles;
        $user->department_name = $user->userDept->department_name ?? "";
        $user->hidden(["userDept"]);
        if (isset($user["other_dept"]) && !empty($user["other_dept"])) {
            $deptIds = (new \catchAdmin\permissions\model\Department())->getDeptByIds($user["other_dept"]);
            if (!empty($deptIds)) {
                array_unshift($deptIds, ['id' => $user->department_id, 'department_name' => $user->department_name, 'is_default' => 1]);
                $user->other_dept = $deptIds;

            }
        }
        // 用户数据权限
        // $user->data_range = Roles::getDepartmentUserIdsBy($roles);
        if (empty($user['avatar'])) {
            $user['avatar'] = '/files/default_avatar.png';
        }
        return CatchResponse::success($user);
    }

    /**
     *
     * @param CreateRequest $request
     * @time 2019年12月06日
     * @return \think\response\Json
     */
    public function save(CreateRequest $request)
    {
       if (empty($request->param('department_id'))) {
            return CatchResponse::fail("部门不能为空");
        }
 
       if ($this->user->getOneData(["doctor_code" => $request->param('doctor_code')], 'id'))
        {
            return CatchResponse::fail("医生编码已存在");
        }

        $this->user->storeBy($request->param());

        $this->user->attachRoles($request->param('roles'));

        if ($request->param('jobs')) {
            $this->user->attachJobs($request->param('jobs'));
        }

        if ($request->param('professionals')) {
            $this->user->attachProfessionals($request->param('professionals'));
        }

        return CatchResponse::success('', '添加成功');
    }

    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @return \think\response\Json
     */
    public function read($id)
    {
        $user = $this->user->findBy($id);
        $user->roles = $user->getRoles();
        $user->jobs = $user->getJobs();
        $user->professionals = $user->getProfessionals();
        return CatchResponse::success($user);
    }

    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @param UpdateRequest $request
     * @return \think\response\Json
     */
    public function update($id, UpdateRequest $request)
    {
        $req  = $request->filterEmptyField()->param();
        if (empty($req['email'])) {
            $req['email'] = '';
        }
        $this->user->updateBy($id, $req);

        if (!empty($request->param('password'))) {
            Redis::getInstance()->redis->del("user:login:".$id);
            Redis::getInstance()->redis->del("user:lock:".$id);
        }

        $user = $this->user->findBy($id);

        $user->detachRoles();
        $user->detachJobs();
        $user->detachProfessionals();

        if (!empty($request->param('roles'))) {
            $user->attachRoles($request->param('roles'));
        }
        if (!empty($request->param('jobs'))) {
            $user->attachJobs($request->param('jobs'));
        }
        if (!empty($request->param('professionals'))) {
            $user->attachProfessionals($request->param('professionals'));
        }
        return CatchResponse::success();
    }

    /**
     *
     * @time 2019年12月04日
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id)
    {
        $ids = Utils::stringToArrayBy($id);

        foreach ($ids as $_id) {
            $user = $this->user->findBy($_id);
            // 删除角色
            $user->detachRoles();
            // 删除岗位
            $user->detachJobs();
            // 删除职称
            $user->detachProfessionals();

            $this->user->deleteBy($_id);
        }

        return CatchResponse::success();
    }

    /**
     *
     * @time 2019年12月07日
     * @param $id
     * @return \think\response\Json
     */
    public function switchStatus($id): \think\response\Json
    {
        $ids = Utils::stringToArrayBy($id);

        foreach ($ids as $_id) {

            $user = $this->user->findBy($_id);

            $this->user->updateBy($_id, [
                'status' => $user->status == Users::ENABLE ? Users::DISABLE : Users::ENABLE,
            ]);
        }

        return CatchResponse::success([], '操作成功');
    }

    /**
     * 导出
     *
     * @time 2020年09月08日
     * @param Excel $excel
     * @param UserExport $userExport
     * @return \think\response\Json
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public function export(Excel $excel, UserExport $userExport)
    {
        return CatchResponse::success($excel->save($userExport, Utils::publicPath('export/users')));
    }

    /**
     * 更新个人信息
     *
     * @time 2020年09月20日
     * @param ProfileRequest $request
     * @return \think\response\Json
     */
    public function profile(ProfileRequest $request)
    {
        $req = $request->filterEmptyField()->param();
        if (empty($req['email'])) {
            $req['email'] = '';
        }
        return CatchResponse::success($this->user->updateBy($request->user()->id, $req));
    }

    public function getDoctorList(CatchRequest $request)
    {
        $data=  $this->user->getDoctorList();

        return CatchResponse::success($data);

    }

    /**
     * 获取人员
     * @return \think\response\Json
     */
    public function getUserList(Request $request): \think\response\Json
    {
//        $req = $request->param();
//        if (empty($req['username'])) {
//            throw new FailedException("用户名不能为空");
//        }
        return CatchResponse::success($this->user->getDatas([],'id,username,doctor_code'));
    }
}
